//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by Fosen on 15/11/29.
//  Copyright © 2015年 fosen. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {

    var account : UserAccount?
    override init() {
        super.init()
        account = UserAccount.loadAccount()
        
    }
    
    //用户是否登录
    var userLogin:Bool {
    
        return account?.access_token != nil
    }
    
    var token : String? {
    
        return account?.access_token
    }
    
    //用户名的计算型属性
    var userName :String? {
    
        return account?.name
    }
    
    var welcomeImageURL:NSURL? {
//    print(account?.avatar_large)
        let url = NSURL(string: account?.avatar_large ?? "")
        return url
    }
    
    
    
    func loadAccessToken(code :String ,finished:(error:NSError?) -> ()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数需要拼装成字典格式
        let parameters = ["client_id" : client_id,"client_secret" : client_secret,"grant_type" : "authorization_code","code" : code,"redirect_uri" : redirect_uri]
        let AFNManager = AFHTTPSessionManager()
        //添加反序列化类型
        AFNManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFNManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            guard let dict = result as? [String : AnyObject] else{
                
                return
            }
            let account = UserAccount(dict: dict)
            //            let token = result["access_token"] as! String
            //            let uid = result["uid"] as! String
            //加载用户数据
            self.loadUserInfo(account, finished: finished)
            
            }) { (_, error) -> Void in
                finished(error: error)
                print(error)
        }
        
    }
    
    func loadUserInfo(account :UserAccount ,finished:(error:NSError?) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let AFNManager = AFHTTPSessionManager()
        //没有数据的时候加载失败  为了保险起见  判断一下
        guard let access_token = account.access_token, userId = account.uid else{
//            SVProgressHUD .showErrorWithStatus("获取网络数据失败，请稍后再试")
            return
        }
        let parameters = ["access_token" : access_token,"uid" : userId]
        AFNManager.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            
            //加？ ！ 需要根据接受类型是什么类型来添加
            account.avatar_large = result["avatar_large"] as? String
            account.name = result["name"] as? String
            
            account.saveAccount()
            finished(error: nil)
            //            print(account)
            }) { (_, error) -> Void in
                
                finished(error: error)
                print(error)
                
        }
        
    }
}
